import { _decorator, Component, sp, Color, tween } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SpineRedBlinkEffect')
export class SpineRedBlinkEffect extends Component {
    @property(sp.Skeleton)
    spine: sp.Skeleton | null = null; // Spine动画组件
    @property
    blinkDuration: number = 0.08; // 单次闪烁持续时间
    @property
    blinkCount: number = 1; // 闪烁次数
    @property
    intensity: number = 1; // 红色强度 (0-1)

    private originalColor: Color | null = null; // 原始颜色

    onLoad() {
        this.blinkDuration = 0.08;
        // 自动获取Spine组件
        if (!this.spine) {
            this.spine = this.getComponent(sp.Skeleton);
        }

        // 保存原始颜色
        if (this.spine) {
            this.originalColor = this.spine.color.clone();
        }

        // let myThis = this;
        // this.schedule(function(){
        //     myThis.startBlink();
        // }.bind(this), 3);
    }

    // 开始闪烁
    startBlink() {
        if (!this.spine || !this.originalColor) return;

        // 停止可能正在进行的闪烁
        this.stopBlink();

        // 创建红色
        const redColor = new Color(
            255,
            255 * (1 - this.intensity),
            255 * (1 - this.intensity),
            this.originalColor.a
        );

        // 闪烁动画
        for (let i = 0; i < this.blinkCount; i++) {
            const delay = i * this.blinkDuration * 2;

            tween(this.spine)
                .delay(delay)
                .to(this.blinkDuration, { color: redColor })
                .to(this.blinkDuration, { color: this.originalColor })
                .start();
        }
    }

    // 停止闪烁
    stopBlink() {
        if (!this.spine || !this.originalColor) return;

        tween(this.spine).stop();
        this.spine.color = this.originalColor.clone();
    }

    // 简单调用示例
    blinkOnce() {
        this.blinkCount = 1;
        this.startBlink();
    }
}